#-*-coding:UTF-8-*-

import datetime
import traceback

from ..logger import logger
from ..ldap import check_LDAP_user_pass
from ..orm.models import *
from ..orm.db_util import get_objects, save_object

class AuthException(Exception):

    def __init__(self,message):
        super(AuthException,self).__init__(message)

def check_userpass(username, password):
    '''return None when passed
    otherwise return string representing reason
    '''
    result = check_LDAP_user_pass(username, password)
    if result:
        return 'user(%s) authentication failed: %s'%(username, result)
    query_result = get_objects(User, name=username)
    if len(query_result) == 0:
        logger.debug('no user(%s) not in DB and insert into DB'%username)
        cur_time = datetime.datetime.now()
        save_object(
            User(name=username, createtime=cur_time, updatetime=cur_time))
    elif len(query_result) > 1:
        raise AuthException('duplicated users(%s) in DB'%username)
    return


def get_login_user_info(username):
    user = get_objects(User, name=username)[0]
    return (user.id, user.name)


def is_user_admin(user_id):
    if user_id and ( int(user_id) == 1 or len(get_objects(UserGroupMapping, user_id=user_id, group_id=1)) > 0):
        return True
    else:
        return False
